/*
    Copyright (c) 2020 Shanghai Macrogiga Electronics Co., Ltd.

    Permission is hereby granted, free of charge, to any person 
    obtaining a copy of this software and associated documentation 
    files (the "Software"), to deal in the Software without 
    restriction, including without limitation the rights to use, copy, 
    modify, merge, publish, distribute, sublicense, and/or sell copies 
    of the Software, and to permit persons to whom the Software is 
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be 
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
    DEALINGS IN THE SOFTWARE.
*/
#include "BSP.h"
#include "mg_api.h"


UART_HandleTypeDef sUartxHandle = {0};
I2C_HandleTypeDef i2c_test = {0};

unsigned char AtcmdFlag = 0;
unsigned char SleepStop = 0x00; //0-no sleep, 1-sleep
unsigned int StandbyTick = 0;
unsigned char UseUart = 0;

static void GPIO_Init(void)
{
    GPIO_InitTypeDef gpioinitstruct={0};

    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_GPIOB_CLK_ENABLE();
    __HAL_RCC_GPIOC_CLK_ENABLE();
    __HAL_RCC_GPIOD_CLK_ENABLE();
    
    //config 3 output pins for application
    gpioinitstruct.Pin  = CONN_PIN;
    gpioinitstruct.Mode = GPIO_MODE_OUTPUT;
    gpioinitstruct.OpenDrain = GPIO_PUSHPULL;
    gpioinitstruct.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    gpioinitstruct.SlewRate = GPIO_SLEW_RATE_LOW;
    gpioinitstruct.DrvStrength = GPIO_DRV_STRENGTH_LOW;
    gpioinitstruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(CONN_GPIO, &gpioinitstruct);
    HAL_GPIO_WritePin(CONN_GPIO,CONN_PIN,GPIO_PIN_RESET);
    
    gpioinitstruct.Pin  = I2CREQ_PIN;
    gpioinitstruct.Mode = GPIO_MODE_OUTPUT;
    gpioinitstruct.OpenDrain = GPIO_PUSHPULL;
    gpioinitstruct.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    gpioinitstruct.SlewRate = GPIO_SLEW_RATE_LOW;
    gpioinitstruct.DrvStrength = GPIO_DRV_STRENGTH_LOW;
    gpioinitstruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(I2CREQ_GPIO, &gpioinitstruct);
    HAL_GPIO_WritePin(I2CREQ_GPIO,I2CREQ_PIN,GPIO_PIN_RESET);
    
    gpioinitstruct.Pin  = STANDBY_PIN;
    gpioinitstruct.Mode = GPIO_MODE_OUTPUT;
    gpioinitstruct.OpenDrain = GPIO_PUSHPULL;
    gpioinitstruct.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    gpioinitstruct.SlewRate = GPIO_SLEW_RATE_LOW;
    gpioinitstruct.DrvStrength = GPIO_DRV_STRENGTH_LOW;
    gpioinitstruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(STANDBY_GPIO, &gpioinitstruct);
    HAL_GPIO_WritePin(STANDBY_GPIO,STANDBY_PIN,GPIO_PIN_SET);
    
    //config 4 input pins for application
    gpioinitstruct.Pin = PORT_PIN;
    gpioinitstruct.Pull = GPIO_PULLUP;//GPIO_NOPULL
    gpioinitstruct.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    gpioinitstruct.SlewRate = GPIO_SLEW_RATE_LOW;
    gpioinitstruct.DrvStrength = GPIO_DRV_STRENGTH_LOW;
    gpioinitstruct.Mode   = GPIO_MODE_INPUT;
    HAL_GPIO_Init(CONFIG_GPIO, &gpioinitstruct);

    gpioinitstruct.Pin = ATMODE_PIN;
    gpioinitstruct.Pull = GPIO_PULLUP;//GPIO_NOPULL
    gpioinitstruct.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    gpioinitstruct.SlewRate = GPIO_SLEW_RATE_LOW;
    gpioinitstruct.DrvStrength = GPIO_DRV_STRENGTH_LOW;
    gpioinitstruct.Mode   = GPIO_MODE_INPUT;
    HAL_GPIO_Init(CONFIG_GPIO, &gpioinitstruct);
    
    gpioinitstruct.Pin = BAUD_PIN;
    gpioinitstruct.Pull = GPIO_PULLUP;//GPIO_NOPULL
    gpioinitstruct.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    gpioinitstruct.SlewRate = GPIO_SLEW_RATE_LOW;
    gpioinitstruct.DrvStrength = GPIO_DRV_STRENGTH_LOW;
    gpioinitstruct.Mode   = GPIO_MODE_INPUT;
    HAL_GPIO_Init(CONFIG_GPIO, &gpioinitstruct);
    
    gpioinitstruct.Pin = WAKEUP_PIN;
    gpioinitstruct.Pull = GPIO_PULLUP;//GPIO_NOPULL
    gpioinitstruct.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    gpioinitstruct.SlewRate = GPIO_SLEW_RATE_LOW;
    gpioinitstruct.DrvStrength = GPIO_DRV_STRENGTH_LOW;
    gpioinitstruct.Mode   = GPIO_MODE_INPUT;
    HAL_GPIO_Init(WAKEUP_GPIO, &gpioinitstruct);
    
    
    //don't change code below.
    gpioinitstruct.Pin = IRQ_PIN;
    gpioinitstruct.Pull = GPIO_PULLUP;
    gpioinitstruct.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    gpioinitstruct.SlewRate = GPIO_SLEW_RATE_LOW;
    gpioinitstruct.DrvStrength = GPIO_DRV_STRENGTH_HIGH;
    gpioinitstruct.Mode   = GPIO_MODE_INPUT;
    HAL_GPIO_Init(IRQ_GPIO, &gpioinitstruct);

    /* Configure pin as input with External interrupt */
    gpioinitstruct.Mode   = EXTI_MODE;
    gpioinitstruct.Exti.Enable = GPIO_EXTI_INT_ENABLE;
    gpioinitstruct.Exti.EdgeLevelSel = GPIO_EXTI_INT_EDGE;
    gpioinitstruct.Exti.RiseFallSel = GPIO_EXTI_INT_LOWFALL;
    HAL_GPIO_Init(IRQ_GPIO, &gpioinitstruct);

    __HAL_GPIO_EXTI_CLEAR_FLAG(IRQ_GPIO, IRQ_PIN);
    /* Enable and set Button EXTI Interrupt to the lowest priority */
    HAL_NVIC_SetPriority(GPIOB_IRQn, PRIORITY_LOW);
    HAL_NVIC_EnableIRQ(GPIOB_IRQn);
}

void SystemClock_Config(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};	
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
    
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HIRC;
    RCC_OscInitStruct.HIRCState = RCC_HIRC_ON;
    RCC_OscInitStruct.HIRCCalibrationValue = RCC_HIRCCALIBRATION_24M;
    
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
        Error_Handler();
    }
    
    /**Initializes the CPU, AHB and APB busses clocks 
    */
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HIRC;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV1;
    RCC_ClkInitStruct.APBCLKDivider = RCC_PCLK_DIV1;
    
    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct) != HAL_OK)
    {
        Error_Handler();
    }
}

void HAL_UART_MspInit(UART_HandleTypeDef *huart)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};

    __HAL_RCC_UARTx_GPIO_CLK_ENABLE();
    /**if UARTx
    UART0    GPIO Configuration:
    PA1     ------> UART0_RXD
    PA2     ------> UART0_TXD
    */
    GPIO_InitStruct.Pin = UARTx_RX_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF;
    GPIO_InitStruct.OpenDrain = GPIO_PUSHPULL;	
    GPIO_InitStruct.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    GPIO_InitStruct.SlewRate = GPIO_SLEW_RATE_HIGH;
    GPIO_InitStruct.DrvStrength = GPIO_DRV_STRENGTH_HIGH;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Alternate = UARTx_RX_ALTERNATE_AFn;
    HAL_GPIO_Init(UARTx_RX_PORT, &GPIO_InitStruct);
    
    GPIO_InitStruct.Pin = UARTx_TX_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF;
    GPIO_InitStruct.Alternate = UARTx_TX_ALTERNATE_AFn;
    HAL_GPIO_Init(UARTx_TX_PORT, &GPIO_InitStruct);
}

void Uart_Init(void)
{
    /* Peripheral clock enable */
    __HAL_RCC_UARTx_CLK_ENABLE();
    
    sUartxHandle.Instance = UARTx;
    if (HAL_GPIO_ReadPin(CONFIG_GPIO,BAUD_PIN))
    {
        sUartxHandle.Init.BaudRate = 115200;
    }
    else
    {
        sUartxHandle.Init.BaudRate = 9600;
    }
    sUartxHandle.Init.BaudDouble = UART_BAUDDOUBLE_ENABLE;
    sUartxHandle.Init.WordLength = UART_WORDLENGTH_8B;
    sUartxHandle.Init.Parity = UART_PARITY_NONE;
    sUartxHandle.Init.Mode = UART_MODE_TX_RX;
    HAL_UART_Init(&sUartxHandle);
    
    //HAL_UART_Transmit_IT(&sUartxHandle, ucSendData, sizeof(ucSendData));
    //HAL_UART_Receive_IT(&sUartxHandle, ucReceiveData, sizeof(ucReceiveData));	
    UARTx->SCON  |= UART_INTSR_RI | UART_INTSR_TI;
    HAL_NVIC_EnableIRQ(UARTx_IRQn);
}

void I2C_Init(void)
{
    GPIO_InitTypeDef  gpioi2c={0};
    
    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_I2C_CLK_ENABLE();
    
    gpioi2c.Pin = GPIO_PIN_1 | GPIO_PIN_2;
    gpioi2c.Mode = GPIO_MODE_AF;
    gpioi2c.Alternate = GPIO_AF4_I2C_SCL;
    gpioi2c.OpenDrain = GPIO_PUSHPULL;
    gpioi2c.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    gpioi2c.SlewRate = GPIO_SLEW_RATE_LOW;
    gpioi2c.DrvStrength = GPIO_DRV_STRENGTH_LOW;
    gpioi2c.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &gpioi2c);
    
    /*set init handle*/

    i2c_test.Instance = I2C;
     
    i2c_test.Init.master = I2C_MASTER_MODE_DISABLE;
    i2c_test.Init.slave = I2C_SLAVE_MODE_ENABLE;
    i2c_test.Mode = HAL_I2C_MODE_SLAVE;
    /* Set interrupt priority and turn on interrupt*/
    HAL_NVIC_SetPriority(I2C_IRQn, PRIORITY_LOW);
    HAL_NVIC_EnableIRQ(I2C_IRQn);
    
    i2c_test.Init.broadack = I2C_BROAD_ACK_ENABLE;
    i2c_test.Init.speedclock = /*I2C_SPEED_RATE*/100;
    i2c_test.Init.slaveAddr = /*I2C_SLAVE_ADDRESS*/0x50;
    i2c_test.State == HAL_I2C_STATE_RESET;
    
    HAL_I2C_Init(&i2c_test);
}

void BSP_Init(void)
{
    HAL_Init();
    SystemClock_Config();
    SPIM_Init();
    GPIO_Init();
    //Delay
    
    UseUart = HAL_GPIO_ReadPin(CONFIG_GPIO,PORT_PIN);
    if (UseUart)
    {
        Uart_Init();
        AtcmdFlag = HAL_GPIO_ReadPin(CONFIG_GPIO,ATMODE_PIN);
    }
    else
    {
        I2C_Init();
    }
    
    if(0 == AtcmdFlag)
    {
        if(GPIO_PIN_RESET == HAL_GPIO_ReadPin(WAKEUP_GPIO,WAKEUP_PIN))
            SleepStop = 1;
    }
    
    LPTIM_Init(LIRC_VALUE);
}

void IrqMcuGotoSleepAndWakeup(void)
{
    if(ble_run_interrupt_McuCanSleep() || (0xffffffff == StandbyTick))
    {
        if ((StandbyTick > 5000)&&(StandbyTick < 0xffffffff))
        {
            StandbyTick = 0xffffffff;
            //radio_standby();
            ble_set_adv_enableFlag(0);
            HAL_GPIO_WritePin(STANDBY_GPIO,STANDBY_PIN,GPIO_PIN_RESET);
        }
        
        if (SleepStop)
        { //sleep
            SCB->SCR &= 0xfb;
            __WFI();
        }
    }
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */

  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{ 
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
